//
//  WBStatusViewModel.swift
//  Weibo
//
//  Created by xu on 2017/3/24.
//  Copyright © 2017年 xuantong. All rights reserved.
//

//view级别 viewmodel
//帮助view的做些数据处理的工具类

//数据-模型-homeModel
import UIKit

class WBStatusViewModel: NSObject {
    //模型属性
    var homeModel: WBHomeModel?{
        
        didSet{
            //设置属性 --逻辑
            // 会员等级设置图片
            
            mbrankImage = dealMbrankImage(mbrank: homeModel?.user?.mbrank ?? 0)
            // 认证
            verifiedImage = dealVerifiedImage(verified: homeModel?.user?.verified ?? 0)
            
            //微博来源
            sourceText = dealSourecText(source:homeModel?.source)
            
            //处理富文本结果赋值
         originalAttributedString = dealContentAttributedString(text: homeModel?.text)
         retweeAttributedString = dealContentAttributedString(text: homeModel?.retweeted_status?.text)
            
        }
    }
    
    
    // 会员等级需要的图片
    var mbrankImage: UIImage?
    // 认证需要的图片
    var verifiedImage: UIImage?
    //微博来源
    var sourceText:String?
    //微博时间
    var createAtText: String?{
        
        return dealSinaTimeText(createAt: homeModel?.created_at)
    }
    
    //原创微博正文富文本
    var originalAttributedString : NSMutableAttributedString?
   //转发微博富文本
    var retweeAttributedString:NSMutableAttributedString?
    
    
    
}

extension WBStatusViewModel {
    
    fileprivate func dealSourecText(source:String?)->String {
        
        guard let s = source, s.contains("\">")  else {
            
            return "来自 那遥远的地方"
        }
        //获取字符串光标的位置
        let startIndex = s.range(of: "\">")!
        let endIndex = s.range(of: "</")!
        // 通过光标位置截取字符串
        let result = s.substring(with: startIndex.upperBound..<endIndex.lowerBound)
        
        
        return  "来自 "+result
    }
    
}



//MARK:处理微博时间业务逻辑
extension WBStatusViewModel {
    
    fileprivate func dealSinaTimeText(createAt:Date?)->String? {
        
        //判断时间的date是否为nil
        guard let sinaDate = createAt else {
            return nil
        }
        
        // 时间格式化
        let df = DateFormatter()
        
        //判断是否是今年
        let isThisYear = dealSinaDateIsThisYear(sinaDate:sinaDate)
        
        // 如果是今年
        if isThisYear {
            // 使用日历lei
            let calender = Calendar.current
            
            // 如果是今天
            if calender.isDateInToday(sinaDate) {
                
                // 计算当前时间和微博时间的差值
                let s = Int(Date().timeIntervalSince(sinaDate))
                
                 // 如果小于等于60s 显示 刚刚
                if s<60 {
                    return "刚刚"
                }else if s > 60 && s <= 60*60{
                    return "\(s/60)分钟前"
                }else {
                    return "\(s/3600)小时前"
                 }
        }else if calender.isDateInYesterday(sinaDate){
                
              df.dateFormat = "昨天 hh:mm"
                
            }else{
                
                // 其他 格式: 12月12日 12:12
                // 指定日期格式
            df.dateFormat = "MM月dd日 hh:mm"
            }
        }else{
            //其他年的处理
             df.dateFormat = "yyyy年MM月dd日 hh:mm"
    }
        
        //得到日期的字符串将其返回
        let result = df.string(from: sinaDate)
        return result
}
    
    
    
    // 处理微博日期是否是今年
    fileprivate func dealSinaDateIsThisYear(sinaDate:Date)->Bool {
        // 时间格式化
        let df = DateFormatter()
        // 指定日期格式
        df.dateFormat = "yyyy"
        // 通过微博日期转微博日期字符串
        let sinaDateStr = df.string(from: sinaDate)
        // 通过当前时间日期转当前日期字符串
        let currentDateStr = df.string(from: Date())
        
        // 判断是否相等
        return sinaDateStr == currentDateStr
    }
    
    
    
}

//MARK: 会员等级图片处理
extension WBStatusViewModel {
    
    fileprivate func dealMbrankImage(mbrank:Int)->UIImage?{
        
        if mbrank > 0 && mbrank < 7 {
            return UIImage (named:"common_icon_membership_level\(mbrank)")
            
        }
        return UIImage(named: "common_icon_membership")
    }
}




extension WBStatusViewModel {

    
    func dealContentAttributedString(text:String?)->NSMutableAttributedString?{
        
        //判断
        guard let t = text else {
            return nil
        }
        
        
        //通过字符串实例化一个可变富文本
        let allAttributedString = NSMutableAttributedString(string: t)
        
        // 使用正则表达式匹配图片表情描述
        let matchResult = try! NSRegularExpression(pattern:"\\[[\\w]+\\]", options: []).matches(in: t, options: [], range:NSRange(location: 0, length: t.characters.count))
        
        // 遍历结果集合
        for match in matchResult.reversed() {
            //匹配结果
            let result = (t as NSString).substring(with:match.range)
            //通过图片描述获取对应的模型
            let emotionModel = WBEmoticonTools.shared.getEmoticonModelWithEmoticons(chs: result)
            //如果是图片表情/
            let allPath = emotionModel?.allPath ?? ""
            //通过路径得到图片
            let image = UIImage(named:allPath,in:WBEmoticonTools.shared.emoticonsBundle,compatibleWith:nil)
            
            //计算行高
            let lineHeight = UIFont.systemFont(ofSize: 14).lineHeight
            //创建文本附件
            let att = WBTextAttachment()
            //设置文本附件属性
            att.image = image
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            //c创建一个不可变的富文本
            let attr = NSAttributedString(attachment: att)
            
            //进行替换
            allAttributedString.replaceCharacters(in: match.range, with: attr)
            
            //匹配用户
            
            //匹配用户：@[a-zA-Z0-9\\u4e00-\\u9fa5_\\-]+
            setTextHighlight(pattern: "@[a-zA-Z0-9\\u4e00-\\u9fa5_\\-]+", allAttributedString: allAttributedString)
            //匹配话题：#[^#]+#
            setTextHighlight(pattern: "#[^#]+#", allAttributedString: allAttributedString)
            //匹配URL：([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?
            setTextHighlight(pattern: "([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", allAttributedString: allAttributedString)
            // 设置富文本字体大小
            allAttributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: FONTSIZEOFNORMAL), range: NSRange(location: 0, length: allAttributedString.length))

            
            
            
            
        }
        return allAttributedString
    }

    
    
    // 设置富文本高亮效果
    func setTextHighlight(pattern:String,allAttributedString:NSMutableAttributedString){
        //获取正则表达式匹配结果集合
        let matchResult = try! NSRegularExpression(pattern: pattern, options: []).matches(in:allAttributedString.string, options: [], range: NSRange(location: 0, length:allAttributedString.string.characters.count))
        
        //点击高亮背景
        let border = YYTextBorder(fill: UIColor.gray, cornerRadius: 2)
        border.insets = UIEdgeInsetsMake(1, 0, 0, 0)
        //s设置高亮
        let higlight = YYTextHighlight()
        
        //设置高亮时候的文字颜色
        higlight.setColor(UIColor.white)
        higlight.setBackgroundBorder(border)
        
        
        //遍历集合
        for match in matchResult {

            // 符文本设置成红色

            allAttributedString.addAttribute(NSForegroundColorAttributeName,value:UIColor.red, range:match.range)
            //把"高亮"属性设置到某个文本范围
             allAttributedString.yy_setTextHighlight(higlight, range: match.range)
            
            
        }
        
    }
    
}

//MARK:处理认证类型 -1：没有认证，1，认证用户，2,3,5: 企业认证，220: 达人
extension WBStatusViewModel{
    fileprivate func dealVerifiedImage(verified:Int)->UIImage?{
        
        switch verified {
        case 1:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return UIImage(named: "avatar_vgirl")
        }
    }
}
